// typeof用以获取一个变量或者表达式的类型，typeof一般只能返回如下几个结果：
// number,boolean,string,function（函数）,object（NULL,数组，对象）,undefined

let store = localStorage;

const get = (key,callback) => {
    let value = store.getItem(key);
    if(typeof(value) ===  'string'){
        value = JSON.parse(value);
    }
    if(callback){callback(value)}
};

const save = (key, value, callback) => {
    store.setItem(key,JSON.stringify(value));
    if(callback){callback(value)}
};

const update = function (key, value, callback) {
    store.setItem(key,JSON.stringify(value));
    if(callback){callback(value)}
};

const del = function (key,callback) {
    store.removeItem(key);
    if(callback){callback(null)}
};


const getItem = (key, itemKey, itemValue,callback)=>{
    get(key,(list)=>{
        if(list === null){
            list = [];
        }

        for(let i=0; i<list.length; i++){
            let li = list[i];
            if(li[itemKey] === itemValue){
                if(callback) callback(li);
                return;
            }
        }

        if(callback) callback(null);
    });
};

const saveItem = (key, payload, callback)=>{
    get(key,(list)=>{
        if(list === null || list === 'undefined'){
            list = [];
        }

        list.push(payload);

        save(key,list,(stores)=>{
            if(callback) callback(stores);
        });
    });
};

const delItem = (key, itemKey, itemValue, callback)=>{
    get(key,(list)=>{
        if(list === null){
            return;
        }

        for(let i=0; i<list.length; i++){
            let li = list[i];
            if(li[itemKey] === itemValue){
                list.splice(i,1);
                break;
            }
        }

        save(key,list,(stores)=>{
            if(callback) callback(stores);
        });
    });
};

const updateItem = (key, itemKey, itemValue, payload, callback)=>{
    get(key,(list)=>{
        if(list === null){
            list = [];
        }

        for(let i=0; i<list.length; i++){
            if(list[i][itemKey] === itemValue){
                list[i] = {...list[i],...payload};
                break;
            }
        }
        save(key,list,(stores)=>{
            if(callback) callback(stores);
        });
    });
};


export default {
    get,
    save,
    update,
    del,
    getItem,
    saveItem,
    updateItem,
    delItem
}